package com.tange.ai.core.demo.add.ap;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.tange.ai.core.demo.LoginActivity;
import com.tange.ai.core.demo.R;
import com.tange.ai.core.demo.Utils;
import com.tange.ai.core.demo.databinding.ActivityWifiConfigurationBinding;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.module.add.ap.DefaultApMatchRule;
import com.tange.module.add.ap.DeviceApScanner;

import java.util.ArrayList;
import java.util.List;

/**
 * WiFi配置
 */
public class WiFiConfigurationActivity extends AppCompatActivity {

    public static final String DEVICE_AP_NAME = "DEVICE_AP_NAME";
    public static final String WIFI_NAME = "WIFI_NAME";
    public static final String WIFI_PASSWORD = "WIFI_PASSWORD";

    private ActivityWifiConfigurationBinding binding;

    private DeviceApScanner deviceApScanner;

    private ApListAdapter wifiListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityWifiConfigurationBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        getSupportActionBar().hide();

        Utils.setStatusBar(this, Color.TRANSPARENT);

        wifiListAdapter = new ApListAdapter();
        wifiListAdapter.onWiFiSelectedListener = new OnWiFiSelectedListener() {
            @Override
            public void onSelected(String wifiName) {
                binding.wifiName.setText(wifiName);
            }
        };
        binding.wifiList.setAdapter(wifiListAdapter);
        binding.wifiList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        String preWifiName = PreferenceUtil.getString(this, WIFI_NAME, "");
        String preWifiPwd = PreferenceUtil.getString(this, WIFI_PASSWORD, "");

        binding.wifiName.setText(preWifiName);
        binding.wifiPwd.setText(preWifiPwd);

        binding.next.setOnClickListener(view -> {

            String wifiName = binding.wifiName.getText().toString();
            String wifiPwd = binding.wifiPwd.getText().toString();

            if (TextUtils.isEmpty(wifiName)) {
                Toast.makeText(view.getContext(), "填写WIFI信息！", Toast.LENGTH_SHORT).show();
                return;
            }

            PreferenceUtil.setString(this, WIFI_NAME, wifiName);
            PreferenceUtil.setString(this, WIFI_PASSWORD, wifiPwd);

            Intent intent = new Intent(view.getContext(), DeviceNetworkConfigurationActivity.class);
            intent.putExtra(DEVICE_AP_NAME, getIntent().getStringExtra(DEVICE_AP_NAME));
            intent.putExtra(WIFI_NAME, wifiName);
            intent.putExtra(WIFI_PASSWORD, wifiPwd);
            startActivity(intent);
            finish();
        });

        startScan();
    }

    private void startScan() {
        if (deviceApScanner == null) {
            deviceApScanner = DeviceApScanner.create(this,
                    new DefaultApMatchRule("AICAM_"), // 使用默认的匹配规则：前缀匹配，此处设置为 AICAM
                    new DeviceApScanner.Callback() {
                        @Override
                        public void onDeviceApRefresh(List<ScanResult> apList) {
                            // 这里获取扫描到的AP
                        }

                        @Override
                        public void onWiFiRefresh(List<ScanResult> wifiList) {
                            // 这里获取扫描到的WiFi（除AP）
                            if (wifiList != null && wifiList.size() > 0) {
                                binding.wifiEmptyView.setVisibility(View.GONE);
                            }
                            wifiListAdapter.refreshApList(wifiList);
                        }

                        @Override
                        public void onError(int errorCode) {
                        }

                        @Override
                        public void onFinish() {

                        }
                    });

            // 自定义：扫描5次
            deviceApScanner.setMaxScanCount(5);
        }

        deviceApScanner.startScan();
        binding.wifiEmptyView.setVisibility(View.VISIBLE);
    }

    public interface OnWiFiSelectedListener {
        void onSelected(String wifiName);
    }

    public class ApListAdapter extends RecyclerView.Adapter<DeviceApScanActivity.ViewHolder> {

        private List<ScanResult> apList = new ArrayList<>();

        private OnWiFiSelectedListener onWiFiSelectedListener;

        public ApListAdapter() {
        }

        public void refreshApList(List<ScanResult> list) {
            this.apList.clear();
            this.apList.addAll(list);
            notifyDataSetChanged();
        }

        @Override
        public DeviceApScanActivity.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_scan_ap, viewGroup, false);
            return new DeviceApScanActivity.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(DeviceApScanActivity.ViewHolder viewHolder, final int position) {
            final String apName = apList.get(position).SSID;
            viewHolder.textView.setText(apName);
            viewHolder.itemView.setOnClickListener(view -> {
                onWiFiSelectedListener.onSelected(apName);
            });
        }

        @Override
        public int getItemCount() {
            return apList.size();
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public final TextView textView;

        public ViewHolder(View view) {
            super(view);
            textView = view.findViewById(R.id.ap_name);
        }
    }
}